package cn.regexp.marktag.utils;

import cn.hutool.core.io.FileUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VFileProperty;
import com.intellij.openapi.vfs.VirtualFile;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 * @author Regexpei
 * @date 2024/5/1 13:12
 * @description
 */
public class CoreFileUtils {

    public static final String CORE_FILE_NAME = "coreFile.txt";

    public static List<String> readFile(Project project) {
        synchronized (CoreFileUtils.class) {
            String coreFilePath = getCoreFilePath(project);
            File file = new File(coreFilePath);
            if (FileUtil.exist(file)) {
                return FileUtil.readLines(file, Charset.defaultCharset());
            }
        }
        return Collections.emptyList();
    }

    public static void writeFile(Project project, List<String> coreFiles) {
        synchronized (CoreFileUtils.class) {
            String coreFilePath = getCoreFilePath(project);
            File file = new File(coreFilePath);
            List<String> list = FileUtil.readLines(file, Charset.defaultCharset());
            list.addAll(coreFiles);
            FileUtil.writeLines(new HashSet<>(list), new File(coreFilePath), Charset.defaultCharset());
        }
    }

    public static String getCoreFilePath(Project project) {
        return project.getBasePath() + File.separator + CORE_FILE_NAME;
    }



    @SuppressWarnings("UnsafeVfsRecursion")
    public static void collectFiles(VirtualFile dir, List<VirtualFile> files) {
        for (VirtualFile file : dir.getChildren()) {
            if (file.isDirectory()) {
                // 递归处理子目录
                collectFiles(file, files);
            } else if (!file.isDirectory() && file.exists() && file.isValid() && !file.is(VFileProperty.SYMLINK)) {
                // 过滤掉非文件、不存在的、无效的和符号链接的文件
                files.add(file);
            }
        }
    }
}
